package com.jack.module.jetpack.datastore.proto

import android.content.Context
import androidx.datastore.DataStore
import androidx.datastore.createDataStore
import com.jack.module.jetpack.UserInfo
import com.jack.module.jetpack.datastore.UserInfoProto
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first

/**
 * @author: dingfeng
 * @date: 2020-10-29
 * @since: 1.0.0
 **/
object DataStoreProto {

    const val user_info_proto_name = "user_pros.pb"

    private lateinit var mDataStore: DataStore<UserInfoProto>

    fun init(context: Context) {
        mDataStore =
                context.createDataStore(
                        fileName = user_info_proto_name,
                        serializer = UserInfoSerializer
                )
    }

    suspend fun saveProInfo(value: String) {
        mDataStore.updateData { preferences ->
            preferences.toBuilder().setId(110).setName(value).setAge(39).setPhone("119120").build()
        }
    }

    suspend fun readProInfo(): String {
        val userPreferencesFlow: Flow<UserInfoProto> = mDataStore.data
        return userPreferencesFlow.first().toString()
    }

    suspend fun saveUserInfo(user: UserInfo) {
        mDataStore.updateData { preferences ->
            preferences.toBuilder()
                    .setId(user.id)
                    .setName(user.name)
                    .setAge(user.age)
                    .setPhone(user.phone)
                    .build()
        }
    }

    suspend fun readUserInfo(): UserInfo {
        val userPreferencesFlow: Flow<UserInfoProto> = mDataStore.data
        val proto = userPreferencesFlow.first()
        return UserInfo(id = proto.id, name = proto.name, age = proto.age, phone = proto.phone)
    }

}